# @Time  :2021/5/27 21:26
# @Author: Houtaroy
from werkzeug.security import check_password_hash
from flask import request
from flask_restx import Namespace, Resource
from flask_jwt_extended import create_access_token, get_jwt_identity, get_jwt

from flask_koala.core.exceptions import BusinessException
from flask_koala.core import RestResult
from flask_koala.system.models import User

from .models import UserAuthority
from .handlers import authorization

auth = Namespace('auth', '认证管理')


@auth.route('/login')
@auth.hide
class Login(Resource):
    def post(self):
        data = request.get_json()
        user = User.get_by_username(data['username'])
        if not check_password_hash(user.password, data['password']):
            raise BusinessException('密码错误')
        authority = UserAuthority.get(user.id)
        authority.post_init()
        access_token = create_access_token(identity=user, additional_claims={
            'permissions': authority.permissions,
            'authorities': authority.authorities
        })
        return RestResult.success({'access_token': access_token, 'type': 'bearer'})


@auth.route('/info')
class Info(Resource):
    @authorization(code='api:auth:info')
    def get(self):
        """
        获取用户信息
        :return: 用户信息实体
        """
        return RestResult.success(get_jwt_identity())


@auth.route('/permissions')
@auth.hide
class Permissions(Resource):
    @authorization(code='api:auth:permissions')
    def get(self):
        return RestResult.success(get_jwt()['permissions'])
